/*
 * @Date: 2022-07-11 14:27:16
 * @LastEditTime: 2023-03-15 09:16:49
 */
import { useUserStore } from '@/store/index';
import { message } from 'ant-design-vue';
// import { md5 } from 'md5js';
import dayjs from 'dayjs';

/**
 * @description: 文件上传
 * @param {*} api
 * @return {*}
 */
export function myApi(api) {
  const counter = useUserStore();
  const unix = dayjs().unix();
  const sign = md5(btoa(unix + 'nitouche'), 32);

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(api.method, api.url, true);

    xhr.setRequestHeader('iv', unix);
    xhr.setRequestHeader('sign', sign);
    xhr.setRequestHeader('token', counter.token);
    xhr.setRequestHeader('Cache-Control', 'no-cache');

    xhr.send(api.formData);
    xhr.onload = async function () {
      const res = JSON.parse(xhr.response);
      if (res.code === 200) resolve(res);
      else {
        reject(res);
        message.warning(res.msg, 2);
      }
    };
  });
}

/**
 * @description: 内容拼接
 * @param {*} data
 * @return {*}
 */
export function parameterChange(data) {
  let res = ``;
  for (const key in data) {
    let dataKey = '';
    if (data[key] || data[key] === 0) dataKey = data[key];
    res = `${res}&${key}=${dataKey}`;
  }
  return res.substr(1);
}
